class User < ActiveRecord::Base
  before_save :crypte_password
  
  
  #数据库 不保存明文密码是所以 需要手工声明 password属性
  attr_accessor :password, :password_confirmation
  validates_confirmation_of :password
  
  validates_presence_of :email, :name, :password
  
  validates_uniqueness_of :email
  validates_format_of :email, :with => /\A([^@\s] + )@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  validates_length_of :password, :within=> 4..10

 def self.encrypt(password, salt)
     #Digest::SHA1
     Digest::SHA1.hexdigest("--#{salt}--#{password}--")
 end
 def encrypt(password)
   self.class.encrypt(password,salt)
 end
 
 
 
 def authenticated?(password)
   crypted_password == encrypt(password)
 end
   
 def self.authenticate(email,password)
   user = find_by_email(email)
   user && user.authenticated?(password) ? user:nil
 end
 

 private
  def crypte_password
    
    self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{email}--") if new_record?
    self.crypted_password = encrypt(password)

end
